package com.chandra.pos.customer.web;

import com.chandra.pos.customer.dao.entity.Customer;
import com.chandra.pos.customer.exception.CustomerNotFoundException;
import com.chandra.pos.customer.service.ICustomerService;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created with IntelliJ IDEA.
 * Customer: T4671
 * Date: 10/5/13
 * Time: 11:54 AM
 * To change this template use File | Settings | File Templates.
 */

//@ManagedBean(name = "productConverter")
//@RequestScoped
//@FacesConverter(value = "productConverter")
@Named("customerConverter")
@ApplicationScoped
public class CustomerConverter implements Converter {

    @Inject
    ICustomerService customerService;


    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                Long number = Long.parseLong(submittedValue);

             Customer product=   customerService.getCustomerDetail(number) ;

               return   product;

            } catch(CustomerNotFoundException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid player"));
            }
        }


    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((Customer) value).getId());
        }
    }
}
